<!-- # src/App.vue -->
<template>
  <div id="app">
    <div style="position: relative" id="test">
      <tinymceEditor ref="get_essay" />
      <transition name="arrowS">
        <div class="arrow" v-show="arrowShow" @click="msShow">
          <i class="el-icon-d-arrow-left"></i>
        </div>
      </transition>
      <transition name="radioS">
        <div class="input-card" v-show="radioShow" @click="msShow2">下一步</div>
      </transition>
    </div>
    <!-- 遮罩 -->
    <!-- <div id="load" class="load" v-if="showLoad"></div> -->

    <div class="cover">
      <div>
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item label="文章摘要" prop="summary">
            <el-input
              type="textarea"
              placeholder="请输入内容"
              v-model="form.summary"
              maxlength="30"
              show-word-limit
            >
            </el-input>
            <div style="margin-left: 10px">
              <el-button type="warning" plain round size="mini"
                >一键提取</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="文章分类" prop="chooseTag">
            <el-tag
              v-for="tag in dynamicTags"
              :key="tag.id"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag.tag_name }}
            </el-tag>
            <el-select
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @change="handleInputConfirm"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.tag_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
              >+ 新标签</el-button
            >
          </el-form-item>
          <el-form-item label="文章封面" prop="cover_image">
            <el-upload
              class="upload-demo"
              drag
              :action="upUrl"
              :headers="header"
              :on-success="addFeudalSuccess"
              multiple
              :limit="3"
              list-type="picture"
              :file-list="displayImage"
              :on-remove="deleteFeudal"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过三张图片
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="发布时间" prop="radio1">
            <el-radio-group v-model="form.radio1" @input="time_radio_group">
              <el-radio :label="1" border>立即发布</el-radio>
              <el-radio :label="2" border>选择时间</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-for="domain in domains"
            label="发布时间"
            :key="domain.key"
            prop="publish_time"
            :rules="{
              required: true,
              message: '域名不能为空',
              trigger: 'blur',
            }"
          >
            <el-date-picker
              v-model="form.publish_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div class="button_bottom">
        <!-- <el-button round>保 存</el-button> -->
        <el-button type="success" round @click="Publish_news('form', form)"
          >发布新闻</el-button
        >
      </div>
    </div>
    <!-- <el-button type="primary" :loading="loading" @click="ssss"
      >加载中</el-button
    >
    <el-button type="primary" :loading="true" @click="ssss">加载中</el-button> -->
  </div>
</template>

<script>
import tinymceEditor from "@/layout/components/Tinymce/index2.vue";
import * as THREE from "three";

import WAVES from "vanta/src/vanta.waves";
import { mapGetters } from "vuex";
import baseURL from "@/config/index";
import { Loading } from "element-ui";
import { remove } from "js-cookie";
import { getTagList, addNews, getNews, updateNews } from "@/api/news";
export default {
  name: "app",

  data() {
    var validateTag = (rule, value, callback) => {
      if (this.form.tag_id.length == 0) {
        callback(new Error("至少选择一个"));
      } else {
        callback();
      }
    };
    return {
      eassyId: 0,
      loading: false,
      arrowShow: true,
      radioShow: false,

      dynamicTags: [],
      inputVisible: false,
      inputValue: "",

      // 上传
      form: {
        title: "", // 标题
        summary: "", //摘要,
        content: "", //内容
        cover_image: [], //封面
        publish_time: "", //发布时间
        tag_id: [], //标签
        is_recommend: 0,
        is_Home_page: 0,
        is_style: 0,
        status: 0,
        radio1: 0,
      },
      domains: [], //判断是否立即发布
      // disabled: true, //判断是否禁用选择器

      options: [],

      //富文本是否加载完成
      showLoad: true,

      // 表单验证
      rules: {
        title: [
          { required: true, message: "请输入文章名称", trigger: "blur" },
          //  { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        summary: [
          { required: true, message: "请输入文章概述", trigger: "blur" },
        ],
        radio1: [
          {
            required: true,
            message: "选择发布时间",
            trigger: "change",
          },
        ],
        chooseTag: [
          {
            required: true,
            validator: validateTag,
            trigger: ["blur", "change"],
          },
        ],
        publish_time: [
          {
            type: "date",
            required: true,
            message: "请选择时间",
            trigger: "change",
          },
        ],
      },

      // 上传组件图片回显，仅用于回显
      displayImage: [],
    };
  },
  components: {
    tinymceEditor,
  },

  computed: {
    ...mapGetters(["name"]),

    header() {},

    upUrl() {
      return baseURL + "admin/upload";
    },
  },

  created() {
    if (this.$route.params.id != undefined) {
      var eid = this.$route.params.id;
      this.eassyId = eid;
      var id = {
        id: eid,
      };
      // 查看新闻详情
      getNews(id).then((res) => {
        this.form = res.data;
        this.$refs.get_essay.content = this.form.content;
        this.dynamicTags = this.form.tags;
        let tagIdentify = this.dynamicTags.map((item) => {
          return item.id;
        });
        // 获取标签去重
        getTagList().then((response) => {
          const newArr = response.data.filter(
            (item) => !tagIdentify.includes(item.id)
          );
          this.options = newArr;
        });
      });
    } else {
      // 获取标签
      getTagList().then((res) => {
        if (res.data.length > 2) {
          // this.disabled = true;
          this.dynamicTags = res.data.slice(0, 2);
          this.options = res.data.slice(2);
        } else {
          this.dynamicTags = res.data;
        }
      });
    }
  },

  mounted() {
    const that = this;
    // 目标元素
    // 遮罩
    // document.getElementById("test").addEventListener(
    //   "DOMSubtreeModified",
    //   function () {
    //     that.showLoad = false;
    //     loadingInstance.close();
    //   },
    //   false
    // );
    // let loadingInstance = Loading.service({
    //   fullscreen: true,
    //   target: document.getElementById("load"),
    //   background: "rgba(0, 0, 0, 0.8)",
    // });
  },

  methods: {
    //上传封面
    addFeudalSuccess(res, file, fileList) {
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "图片上传成功",
        });
        // var imageUrls = baseURL + res.data;
        var imageUrls = res.data;
        var img = {
            url: imageUrls,
            name: file.name,
          },
          imge2 = {
            url: baseURL + imageUrls,
            name: file.name,
          };
        this.displayImage.push(imge2);
        this.form.cover_image.push(img);
      } else {
        this.$message.error("上传失败");
      }
    },

    // 删除照片
    deleteFeudal(file) {
      // var deleteImg = baseURL + file.response.data;
      // var imageData = this.form.cover_image;
      // this.form.cover_image = imageData.filter((item) => item !== deleteImg);
      var deleteImg = file.url.replace(baseURL, "");
      var deleteImg2 = file.url;
      var imageData = this.form.cover_image;
      this.form.cover_image = imageData.filter(
        (item) => item.url !== deleteImg
      );
      this.displayImage = this.displayImage.filter(
        (item) => item.url !== deleteImg2
      );
    },

    //动态标签
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.options.push({
        id: tag.id,
        tag_name: tag.tag_name,
      });
    },

    //发布时间
    time_radio_group(value) {
      if (value == 2) {
        this.addDomain_time();
      } else {
        this.domains.splice(0);
      }
    },

    //显示选择时间框
    addDomain_time() {
      this.domains.push({
        value: "",
        key: Date.now(),
      });
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.focus();
      });
    },

    // 下拉菜单选择
    handleInputConfirm() {
      let inputValue = this.inputValue;
      // this.options
      let item = this.options.find((item) => {
        return item.id == inputValue;
      });
      if (inputValue) {
        this.dynamicTags.push(item);
        this.options = this.options.filter(function (item) {
          return item.id !== inputValue;
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    msShow() {
      this.arrowShow = !this.arrowShow;
      this.radioShow = !this.radioShow;
    },

    //点击下滑到页面底部
    msShow2() {
      this.radioShow = !this.radioShow;
      this.arrowShow = !this.arrowShow;
      this.$nextTick(() => {
        let dom = document.documentElement;
        window.scrollTo({ behavior: "smooth", top: dom.scrollHeight });
      });
    },

    //发布新闻
    Publish_news(from, data) {
      this.form.content = this.$refs.get_essay.content;
      const tag = this.dynamicTags.map((item) => item.id);
      this.form.tag_id = tag;
      if (this.form.radio1 == 1) {
        var currentDate = new Date();
        var year = currentDate.getFullYear();
        var month = (currentDate.getMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以要加1，并补零
        var day = currentDate.getDate().toString().padStart(2, "0"); // 补零
        var hours = currentDate.getHours().toString().padStart(2, "0"); // 补零
        var minutes = currentDate.getMinutes().toString().padStart(2, "0"); // 补零
        var seconds = currentDate.getSeconds().toString().padStart(2, "0"); // 补零
        var formattedDateTime =
          year +
          "-" +
          month +
          "-" +
          day +
          " " +
          hours +
          ":" +
          minutes +
          ":" +
          seconds;
        this.form.publish_time = formattedDateTime;
      }
      // 上传接口
      this.$refs[from].validate((valid) => {
        if (valid) {
          if (this.$refs.get_essay.content == "") {
            this.$notify.error({
              title: "错误",
              message: "您还未填写正文",
              offset: 100,
            });
          } else {
            if (this.$route.params.id != undefined) {
              this.form.id = this.eassyId;
              updateNews(this.form).then((res) => {
                this.$refs.get_essay.content = "";
                this.$refs[from].resetFields();
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.go(-1);
              });
            } else {
              addNews(data).then((res) => {
                if (res.code == 0) {
                  this.$refs.get_essay.content = "";
                  this.$refs[from].resetFields();
                  this.$message({
                    message: "发布新闻成功",
                    type: "success",
                  });
                  this.$store.dispatch("tagsView/delView", this.$route);
                  this.$router.go(-1);
                }
              });
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
#app {
  position: relative;

  .load {
    background-color: rgb(255, 255, 255);
    width: 100%;
    height: calc(100vh - 84px);
    position: fixed;
    top: 84px;
    z-index: 1310;
  }

  .arrow {
    position: absolute;
    background-color: #409eff;
    height: 80px;
    width: 20px;
    text-align: center;
    right: 0px;
    bottom: 201.46px;
    line-height: 80px;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    cursor: pointer;
    color: #fff;
  }

  .input-card {
    background-color: #fff;
    position: absolute;
    bottom: 201.46px;
    right: 15px;
    padding: 0px 10px;
    border-radius: 20px;
    box-shadow: 0 0 4px 1px rgb(0 0 0 / 20%);
    height: 40px;
    width: 90px;
    text-align: center;
    line-height: 40px;
    font-size: 14px;
    background-color: #409eff;
    color: #fff;
  }

  .arrowS-enter-active {
    animation: arrowNone 0.3s reverse;
  }

  .arrowS-leave-active {
    animation: arrowNone 0.3s;
  }

  @keyframes arrowNone {
    0% {
      transform: translateX(0px);
    }

    100% {
      transform: translateX(20px);
    }
  }

  .radioS-enter-active {
    animation: radioNone 0.3s;
  }

  .radioS-leave-active {
    animation: radioNone 0.3s reverse;
  }

  @keyframes radioNone {
    0% {
      transform: translateX(224px);
    }

    100% {
      transform: translateX(0px);
    }
  }

  .cover {
    width: 100%;
    // height: 800px;
    min-height: calc(100vh - 84px);
    padding: 50px 80px 30px 80px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;

    .close_form {
      height: 30px;
      width: 30px;
      right: 30px;
      // background-color: #409eff;
      position: absolute;
      line-height: 30px;
      top: 10px;
      text-align: center;
      font-size: 20px;
      cursor: pointer;
    }

    .close_form:hover {
      background-color: #ff4040;
      color: #fff;
      border-radius: 50%;
    }

    .button_bottom {
      display: flex;
      justify-content: right;
      padding-right: 100px;
    }

    ::v-deep .el-form-item__content {
      line-height: 17px;
      display: flex;

      .el-button--mini {
        padding: 5px 10px;
        font-size: 10px;
      }

      .el-tag + .el-tag {
        margin-left: 10px;
      }
      .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
      }
      .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
      }
    }

    ::v-deep .el-upload-dragger {
      width: 300px;
      height: 150px;
      border: 1px dashed #898989;
    }
  }
}

::v-deep .el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
::v-deep .el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
</style>